﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.IO;
using WmWebSystem.Models;
using WmWebSystem.Service;

namespace WmWebSystem.DbHelper
{
    public static class FinanceHelper
    {
        public static void BeteiligungToThisProjectOf(string pno,string priceNo, string amount) 
        {
            WmDb mydb = new WmDb();

            DateTime time = DateTime.Now;
            string author = HttpContext.Current.User.Identity.Name;
            decimal price = Convert.ToDecimal(amount);

            Finance f1 = new Finance();
            f1.Price = price;
            f1.AddTime = time;
            f1.ProjectNo = pno;
            f1.PriceType = "支付宝";
            f1.PriceNo = priceNo;

            try
            {
                mydb.Finances.Add(f1);
                mydb.SaveChanges();
                //将记录写入日志
                string p1 = "Add new to Finances, The PriceNo:" + priceNo;
                WriteLog.WriteSysLog(p1);
            }
            catch (FieldAccessException ex)
            {
                //失败，进行回滚操作  记录异常
                WriteLog.WriteSysLog(ex.ToString());
            }
        }

        public static decimal IsArriveTheTarget(string pno, decimal amount)
        {
            var project = ProjectHelper.FindProjectByProjectNo(pno);
            decimal remainder=project.TargetValue-project.CurrentValue;
            if (remainder > amount)
                return amount;
            else
                return remainder;

        }

        public static IEnumerable<Finance> FindFinancesRecordBy(string name)
        {
            WmDb mydb=new WmDb();
            var finances = from f in mydb.Finances
                           where f.Customer == name
                           orderby f.AddTime descending
                           select f;
            return finances;
        }

        public static IEnumerable<Finance> FindAllFinancesRecord()
        {
            WmDb mydb = new WmDb();
            var finances = from f in mydb.Finances
                           orderby f.AddTime descending
                           select f;
            return finances;
        }

    }
}